package com.net.xpay.web.interceptor;

import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.web.secutiry.Operator;
import com.net.shard.ShardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 Eric
 */
public class ShardContextInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserShardManager userShardManager;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse rsp, Object handler) throws Exception {
        Operator user = Operator.getCurrentOperator();
        Long userId = user == null ? null : user.getUserId();
        if (userId != null) {
            UserShard userShard = userShardManager.getById(userId);
            if (userShard != null) {
                ShardUtil.setShardContext(userShard.getShardId());
            }
        }
        return super.preHandle(req, rsp, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse rsp, Object handler, Exception ex) {
        ShardUtil.cleanShardContext();
    }

}
